package com.cjgl.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cjgl.common.BaseResponse;
import com.cjgl.common.ErrorCode;
import com.cjgl.common.ResultUtils;
import com.cjgl.exception.BusinessException;
import com.cjgl.model.dto.adminManage.DeleteByNosRequest;
import com.cjgl.model.dto.student.FuzzySelectStudentVoRequest;
import com.cjgl.model.dto.teacher.FuzzySelectTeacherVoRequest;
import com.cjgl.model.dto.user.UserRequestChangePassword;
import com.cjgl.model.entity.TblScores;
import com.cjgl.model.entity.TblStudents;
import com.cjgl.model.entity.TblTeacher;
import com.cjgl.model.entity.TblUsers;
import com.cjgl.model.vo.student.MajorAndClassNoVo;
import com.cjgl.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangyuwu
 */
@Slf4j
@RestController
@RequestMapping("/adminManageInfos")
public class AdminManageInfoController {
	@Resource
	TblUsersService usersService;
	@Resource
	TblStudentsService studentsService;
	@Resource
	TblTeacherService teacherService;
	@Resource
	TblScoresService scoresService;
	@Resource
	TblCoursestableService coursestableService;

	@Resource
	TblAdminService adminService;
	/**
	 * 结果
	 */
	Boolean res = false;
	/**
	 * 用来判断删除和修改是否成功
	 */
	Boolean userCheck = false;
	Boolean studentCheck = false;
	Boolean scoreCheck = false;
	Boolean teacherCheck = false;


	/**
	 * 重置密码是否成功
	 */
	Integer resetPasswordCheck = 0;

	/**
	 * 添加检查 大于0就是成功
	 */
	Integer insertCheck = 0;
	Integer updateCheck = 0;


	/**
	 * 获取用户表所有信息
	 * 没写成动态sql
	 *
	 * @return
	 */
	@GetMapping("/users")
	public BaseResponse<List<TblUsers>> getUserTableInfo() {
		List<TblUsers> users = usersService.getBaseMapper().selectList(null);
		return ResultUtils.success(users);
	}


	@GetMapping("/getMajorsAndClassNos")
	public BaseResponse<List<MajorAndClassNoVo>> getMajorsAndClassNos() {

		List<MajorAndClassNoVo> majorAndClassNoVoList = new ArrayList<>();



		List<String> majorsAndClassNos = adminService.getMajorsAndClassNos();
		majorsAndClassNos.forEach(e->{
			List<String> classNos = adminService.getClassNos(e);
			List<String> collect = classNos.stream().filter(item -> {
				if (org.springframework.util.StringUtils.isEmpty(item)) {
					return false;
				} else {
					return true;
				}
			}).collect(Collectors.toList());
			MajorAndClassNoVo majorAndClassNoVo = new MajorAndClassNoVo();
			majorAndClassNoVo.setStudentMajor(e);
			majorAndClassNoVo.setStudentClassNo(collect);
			majorAndClassNoVoList.add(majorAndClassNoVo);
		});

		return ResultUtils.success(majorAndClassNoVoList);
	}


	/**
	 * 获取学生信息
	 * 根据 name(姓名) no(学号) gender(性别) address(地址) major(专业) StudentClassNo(班级号)
	 *
	 * @return
	 */
	@PostMapping("/students")
	public BaseResponse<List<TblStudents>> getStudentsInfos(@RequestBody FuzzySelectStudentVoRequest fuzzySelectStudent,
															HttpServletRequest request) {

		log.info("模糊查询条件--->" + fuzzySelectStudent);
		/**
		 * 	模糊查询+动态sql
		 */
		LambdaQueryWrapper<TblStudents> studentQueryWrapper = new LambdaQueryWrapper<>();
		studentQueryWrapper
				.like(!StringUtils.isEmpty(fuzzySelectStudent.getStudentName()), TblStudents::getStudentName,
						fuzzySelectStudent.getStudentName())
				.like(!StringUtils.isEmpty(fuzzySelectStudent.getStudentNo()), TblStudents::getStudentNo,
						fuzzySelectStudent.getStudentNo())
				.eq(!StringUtils.isEmpty(fuzzySelectStudent.getStudentGender()), TblStudents::getStudentGender,
						fuzzySelectStudent.getStudentGender())
				.like(!StringUtils.isEmpty(fuzzySelectStudent.getStudentAddress()), TblStudents::getStudentAddress,
						fuzzySelectStudent.getStudentAddress())
				.like(!StringUtils.isEmpty(fuzzySelectStudent.getStudentMajor()), TblStudents::getStudentMajor,
						fuzzySelectStudent.getStudentMajor())
				.like(!StringUtils.isEmpty(fuzzySelectStudent.getStudentClassNo()), TblStudents::getStudentClassNo,
						fuzzySelectStudent.getStudentClassNo());


		List<TblStudents> studentInfos = studentsService.getBaseMapper().selectList(studentQueryWrapper);
		return ResultUtils.success(studentInfos);
	}

	@GetMapping("/getDepts")
	public BaseResponse<List<String>> getDepts(){


		List<String> depts = adminService.getDepts();

		return ResultUtils.success(depts);

	}

	/**
	 * 获取老师信息
	 *
	 * @return
	 */
	@PostMapping("/teachers")
	public BaseResponse<List<TblTeacher>> getTeacherInfos(@RequestBody FuzzySelectTeacherVoRequest fuzzySelectTeacherVoRequest,
														  HttpServletRequest request) {
		log.info("老师条件查询---->" + fuzzySelectTeacherVoRequest);

		/**
		 * 模糊查询+动态sql
		 * 根据 teacherNo教师号 teacherName教师姓名 teacherGender性别 teacherAddress家庭地址 teacherDeptname院系
		 */
		LambdaQueryWrapper<TblTeacher> teacherQueryWrapper = new LambdaQueryWrapper<>();
		teacherQueryWrapper
				.like(!StringUtils.isEmpty(fuzzySelectTeacherVoRequest.getTeacherNo()), TblTeacher::getTeacherNo,
						fuzzySelectTeacherVoRequest.getTeacherNo())
				.like(!StringUtils.isEmpty(fuzzySelectTeacherVoRequest.getTeacherName()), TblTeacher::getTeacherName,
						fuzzySelectTeacherVoRequest.getTeacherName())
				.eq(!StringUtils.isEmpty(fuzzySelectTeacherVoRequest.getTeacherGender()), TblTeacher::getTeacherGender,
						fuzzySelectTeacherVoRequest.getTeacherGender())
				.like(!StringUtils.isEmpty(fuzzySelectTeacherVoRequest.getTeacherAddress()), TblTeacher::getTeacherAddress,
						fuzzySelectTeacherVoRequest.getTeacherAddress())
				.like(!StringUtils.isEmpty(fuzzySelectTeacherVoRequest.getTeacherDeptname()), TblTeacher::getTeacherDeptname,
						fuzzySelectTeacherVoRequest.getTeacherDeptname());
		List<TblTeacher> teacherInfos = teacherService.getBaseMapper().selectList(teacherQueryWrapper);
		return ResultUtils.success(teacherInfos);
	}

	/**
	 * 接受
	 * 删除相关信息
	 * 删除studet，级联删除user中的信息/teacher相同
	 * 实现方式：1 在后端操作 2 在数据库写触发器操作
	 * 此处使用后端操做（增加学生或者老师信息会在user中自动添加userNo和默认密码123456就是触发器实现的）
	 *
	 * @return
	 */
	@Transactional
	@PostMapping("/delete/user")
	public BaseResponse<Boolean> deleteInfos(@RequestBody DeleteByNosRequest deleteByNos, HttpServletRequest request) {
		log.info("接收到的numbers-->" + deleteByNos);
		if (deleteByNos == null || deleteByNos.getUserNos().size() == 0 || deleteByNos.getType().getClass() != Integer.class) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		Integer deleteType = deleteByNos.getType();
		List<String> userNos = deleteByNos.getUserNos();

		/**
		 * 0 从users删除 失去登陆权限 1 删除学生 2 删除老师
		 */
		// 2023/5/29 业务逻辑可以做优化


		LambdaUpdateWrapper<TblUsers> updateWrapper = new LambdaUpdateWrapper<>();
		LambdaUpdateWrapper<TblStudents> stuUpdateWrapper = new LambdaUpdateWrapper<>();
		LambdaUpdateWrapper<TblScores> scoreUpdateWrapper = new LambdaUpdateWrapper<>();
		LambdaUpdateWrapper<TblTeacher> teaUpdateWrapper = new LambdaUpdateWrapper<>();

		if (deleteType == 0) {
			for (String userNo : userNos) {
				updateWrapper.eq(TblUsers::getUserNo, userNo);
				userCheck = usersService.remove(updateWrapper);
				updateWrapper.clear();
			}
		} else if (deleteType == 1) {
			log.info("删除" + Arrays.toString(userNos.toArray()));

			for (String userNo : userNos) {

				updateWrapper.eq(TblUsers::getUserNo, userNo);
				userCheck = usersService.remove(updateWrapper);
				updateWrapper.clear();

				stuUpdateWrapper.eq(TblStudents::getStudentNo, userNo);
				studentCheck = studentsService.remove(stuUpdateWrapper);
				updateWrapper.clear();

				scoreUpdateWrapper.eq(TblScores::getStudentNo, userNo);
				scoreCheck = scoresService.remove(scoreUpdateWrapper);
				scoreUpdateWrapper.clear();
				res = (userCheck && studentCheck && scoreCheck);
			}
		} else if (deleteType == 2) {
			// 2023/5/29 换老师（逻辑上）
			//没从课程表删除：因为逻辑上会换老师
			for (String userNo : userNos) {

				updateWrapper.eq(TblUsers::getUserNo, userNo);
				userCheck = usersService.remove(updateWrapper);
				updateWrapper.clear();

				teaUpdateWrapper.eq(TblTeacher::getTeacherNo, userNo);
				teacherCheck = teacherService.remove(teaUpdateWrapper);
				teaUpdateWrapper.clear();
				res = (userCheck && teacherCheck);
			}
		} else {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		return ResultUtils.success(res);
	}

	/**
	 * 重置密码-->原则上管理员无需修改用户密码
	 * 原则上一次重置一个密码，所以直接调用修改密码的接口
	 *
	 * @param userRequestChangePassword 用于接userNo 和新 password
	 * @return
	 */
	@PostMapping("/reset")
	public BaseResponse<Boolean> resetUserPassword(@RequestBody UserRequestChangePassword userRequestChangePassword, HttpServletRequest request) {

		String userPassword = userRequestChangePassword.getUserPassword();
		String userNo = userRequestChangePassword.getUserNo();

		//改为默认密码
		resetPasswordCheck = usersService.changeUserPassword(userNo, "123456");
		// 2023/5/29 可以把默认password写入配置文件（清楚明了）
		//resetPasswordCheck = usersService.changeUserPassword(userNo, "${morenpwd}");
		if (resetPasswordCheck > 0) {
			return ResultUtils.success(true);
		}
		return ResultUtils.success(false);
	}

	/**
	 * 添加学生,会自动为user中添加userNo和password(数据库触发器实现)
	 *
	 * @param students
	 * @param request
	 * @return
	 */
	@PostMapping("/addStudent")
	public BaseResponse<Boolean> addStudent(@RequestBody TblStudents students, HttpServletRequest request) {
		if (students == null || students.getStudentNo() == null) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		insertCheck = studentsService.getBaseMapper().insert(students);
		if (insertCheck > 0) {
			return ResultUtils.success(true);
		}

		return ResultUtils.success(false);
	}

	/**
	 * 添加老师,会自动为user中添加userNo和password(数据库触发器实现)
	 *
	 * @param teacher
	 * @param request
	 * @return
	 */
	@PostMapping("/addTeacher")
	public BaseResponse<Boolean> addTeacher(@RequestBody TblTeacher teacher, HttpServletRequest request) {
		if (teacher == null || teacher.getTeacherNo() == null) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		insertCheck = teacherService.getBaseMapper().insert(teacher);
		if (insertCheck > 0) {
			return ResultUtils.success(true);
		}

		return ResultUtils.success(false);
	}


	/**
	 * 修改学生
	 *
	 * @param students
	 * @param request
	 * @return
	 */
	@PostMapping("updateStudent")
	public BaseResponse<Boolean> updateStudent(@RequestBody TblStudents students, HttpServletRequest request) {

		if (students == null || students.getStudentNo() == null) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		//修改学生,返回ture 或 false
		LambdaUpdateWrapper<TblStudents> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(TblStudents::getStudentNo, students.getStudentNo());
		studentCheck = studentsService.update(students, updateWrapper);

		return ResultUtils.success(studentCheck);
	}

	/**
	 * 修改老师
	 *
	 * @param teacher
	 * @param request
	 * @return
	 */
	@PostMapping("/updateTeacher")
	public BaseResponse<Boolean> updateTeacher(@RequestBody TblTeacher teacher, HttpServletRequest request) {

		if (teacher == null || teacher.getTeacherNo() == null) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		LambdaUpdateWrapper<TblTeacher> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(TblTeacher::getTeacherNo, teacher.getTeacherNo());
		teacherCheck = teacherService.update(teacher, updateWrapper);

		return ResultUtils.success(teacherCheck);
	}
}
